package ModelLayer;

import java.util.ArrayList;
import java.util.Iterator;
/**
 * Write a description of class AddressBook here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class AddressBook
{
    // instance variables - replace the example below with your own
    private static AddressBook instance = null;
    private ArrayList<Person> persons;
    /**
     * Constructor for objects of class AddressBook
     */
    private AddressBook()
    {
        // initialise instance variables              
        persons = new ArrayList<Person>();
    }

    public static AddressBook getInstance()
    {
        if(instance == null)
        {
            instance = new AddressBook();
        }
        
        return instance;
    }
    
    public ArrayList<Person> getPersonlist()
    {
        return persons;
    }
    
    
    public void addPerson(Person person)
    {   
        persons.add(person);
    }
    
    public Person getPerson(int id)
    {
        Person thePerson = null;
        boolean found = false;
        Iterator<Person> it = persons.iterator();
        while(it.hasNext() && !found)
        {
            Person person = it.next();
            if(person.getId() == id)
            {
                thePerson = person;
                found = true;
            }
        }        
        return thePerson;
    }
    
    public void removePerson(int id)
    {        
        Person person = getPerson(id);
        if(person != null)
        {
            persons.remove(person);
        }
    }
    
    public void updatePerson(int choise, int id, String value)
    {
        Person person;
        person = getPerson(id);

        if (person != null) {
            if(choise == 1)
            {
                person.setName(value);
            }
            if(choise == 2)
            {
                person.setAddress(value);
            }
            if(choise == 3)
            {
                person.setPostalcode(Long.parseLong(value));
            }
            if(choise == 4)
            {
                person.setCity(value);
            }
            if(choise == 5)
            {
                person.setPhone(Long.parseLong(value));
            }
        }
    }
    
    public void printAddressBook()
    {
        if (persons.size() !=0) {
            for(Person person : persons)
            {
                person.print();
            }
        }
    }
    
}
